package com.jielihaofeng.netty.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author Johnnie Wind
 * @description channel：ChannelFuture 使用
 * @date 2021/11/9 16:32
 */
@Slf4j
public class TestChannel {
    public static void main(String[] args) throws InterruptedException {
        // ChannelFuture
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // connect 是异步非阻塞的方法，主线程发起调用，真正执行connect的是NioEventLoopGroup里的另一个线程
                .connect("127.0.0.1", 8088);
//                .sync()
//                .channel()
//                .writeAndFlush(new Date() + ": hello world!");
        // 1. 没有调sync发不成功
        Channel channel = channelFuture.channel();
        log.debug("{}",channel);
        channel.writeAndFlush(new Date() + ": hello world1!");
        // 2. 调sync，同步处理结果
        Channel syncChannel = channelFuture.sync().channel();
        log.debug("{}",syncChannel);
        syncChannel.writeAndFlush(new Date() + ": hello world2!");
        // 3. addListener，异步回调处理结果
        channelFuture.addListener((ChannelFutureListener)future->{
            System.out.println(future.channel().writeAndFlush(new Date() + ": hello world3!"));
        });
    }
}

// future和promise都是异步方法，去正确处理结果